import Vue from "vue";
import Vuex from "vuex";
import Cookie from "js-cookie";

Vue.use(Vuex);

let minutes = 30;
let expires = new Date(new Date() * 1 + minutes * 1000 * 60); // 三十分钟后过期

export default new Vuex.Store({
  state: {
    account: Cookie.get("account") || null,
    subTotal: null,
    cartList: Cookie.get("cartList") || null,
  },
  getters: {},
  mutations: {
    clearAll(state) {
      state.account = null;
      Cookie.remove("account");
      state.cartList = null;
      Cookie.remove("cartList");
    },
    setAccount(state, val) {
      state.account = JSON.stringify(val);
      Cookie.set("account", state.account, { expires: expires });
    },
    clearAccount(state) {
      state.account = null;
      Cookie.remove("account");
    },
    setCartList(state, cartList) {
      console.log("setCartList");
      let tmpCartList = [];
      tmpCartList = cartList;
      // for (let i = 0; i < cartList.length; i++) {
      //   const element = cartList[i];
      //   console.log("element", element);
      //   tmpCartList.push({
      //     userId: element.userId,
      //     itemId: element.itemId,
      //     productId: element.item.productId,
      //     quantity: parseInt(element.quantity),
      //     listPrice: element.item.listPrice,
      //   });
      // }
      state.cartList = JSON.stringify(tmpCartList);
      Cookie.set("cartList", JSON.stringify(tmpCartList), { expires: expires });
    },
    clearCartList(state) {
      state.cartList = null;
      Cookie.remove("cartList");
    },
  },
  actions: {},
  modules: {},
});
